package pl.mcnova.controller;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import pl.mcnova.McNova;
import pl.mcnova.controller.utils.PropsUtils;

public class MailSender {

	private String user;
	private String password;
	private Transport transport;
	private String text;

	public MailSender(String user, String password) {
		this.user = user;
		this.password = password;
	}

	public MailSender() {

		this.user = McNova.getLogin();
		this.password = McNova.getPass();
	}

	// public static void main(String[] Args) throws MessagingException {
	//
	// new Mail("test7@onet.eu", "test7test7").send("hello world!",
	// "this is mail");
	// }

	public boolean send(String text, String subject, String addressee) {

		try {

			Properties props = new Properties();
			PropsUtils.load(props, PropsUtils.class, "message.properties");

			Authenticator auth = new AccountAuthenticator();

			Session session = Session.getInstance(props, auth);
			session.setDebug(false);

			Message message = new MimeMessage(session);
			message.setText(text);
			message.setSubject(subject);

			InternetAddress address = new InternetAddress(user);
			InternetAddress addressOdbiorcy = new InternetAddress(addressee);

			message.setFrom(address);
			message.setRecipient(Message.RecipientType.TO, addressOdbiorcy);
			message.saveChanges();

			if (props.getProperty("mail.transport.protocol") != null)
				transport = session.getTransport(props.getProperty("mail.transport.protocol"));
			else
				transport = session.getTransport("smtp");

			if (props.getProperty("smtp_host_name") != null)
				transport.connect(props.getProperty("smtp_host_name"), user, password);
			else
				transport.connect("smtp.poczta.onet.pl", user, password);

			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private class AccountAuthenticator extends Authenticator {

		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	}
}
